<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus06.html">Previous Chapter</a>
    <li> <a href="cplusplus08.html">Next Chapter</a>
</ul>
<hr>
<a name="MEMORY"></a><a name="l110"></a>
<h1>Chapter 7: Classes and memory allocation</h1>
<a name="memory"></a>

<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="memory/intro"></a>In contrast to the set of functions which handle <a name="an931"></a>
memory allocation in <strong>C</strong>
(i.e., <a name="an932"></a>
<code>malloc()</code> etc.), the operators <a name="an933"></a>
<code>new</code> and <a name="an934"></a>
<code>delete</code> are
specifically meant to be used with the features that <strong>C++</strong> offers.
Important differences between <code>malloc()</code> and <code>new</code> are:
    <ul>
    <li> The function <code>malloc()</code> doesn't `know' what the allocated memory
will be used for. E.g., when memory for <code>int</code>s is allocated, the programmer
must supply the correct expression using a multiplication by
<code>sizeof(int)</code>. In contrast, <code>new</code> requires the use of a type; the
<a name="an935"></a>
<code>sizeof</code> expression is implicitly handled by the compiler.
    <li> The only way to <a name="an936"></a>
initialize memory which is allocated by
<code>malloc()</code> is to use <a name="an937"></a>
<code>calloc()</code>, which allocates memory and resets it to a
given value. In contrast, <code>new</code> can call the <a name="an938"></a>
constructor of an allocated
object where initial actions are defined. This constructor may be supplied
with arguments.
    <li> All <strong>C</strong>-allocation functions must be inspected for
<a name="an939"></a>
<code>NULL</code>-returns. In contrast, the <code>new</code>-operator provides a facility called
a <a name="an940"></a>
<em>new_handler</em> (cf. section <a href="cplusplus07.html#NEWHANDLER">7.2.2</a>) which can be used instead
of explicitly checking for 0 return values.
    </ul>
    A comparable relationship exists between <a name="an941"></a>
<code>free()</code> and <code>delete</code>:
<code>delete</code> makes sure that when an object is deallocated, a corresponding
destructor is called.
<p>
The automatic calling of constructors and destructors when objects are created
and destroyed, has a number of consequences which we shall discuss in this
chapter. Many problems encountered during <strong>C</strong> program development are caused
by incorrect memory allocation or <a name="an942"></a>
memory leaks: memory is not allocated,
not freed, not initialized, boundaries are overwritten, etc..  <strong>C++</strong> does
not `magically' solve these problems, but it <em>does</em> provide a number of
handy tools.
<p>
Unfortunately, the very frequently used <a name="an943"></a>
<code>str...()</code> functions, like
<a name="an944"></a>
<code>strdup()</code> are all <code>malloc()</code> based, and should therefore preferably
not be used anymore in <strong>C++</strong> programs. Instead, a new set of corresponding
functions, based on the operator <code>new</code>, are preferred. Also, since the class
<code>string</code> is available, there is less need for these functions in <strong>C++</strong>
than in <strong>C</strong>. In cases where operations on <code>char *</code> are preferred or
necessary, comparable functions based on <code>new</code> could be developed. E.g.,
    <a name="STRDUPNEW"></a> for the function <code>strdup()</code> a comparable function
<a name="an945"></a>
 <code>char *strdupnew(char const *str)</code> could be developed as
follows:
        <pre>
    char *strdupnew(char const *str)
    {
        return str ? strcpy(new char [strlen(str) + 1], str) : 0;
    }
</pre>
    In this chapter the following topics will be covered:
    <ul>
    <li> the assignment operator (and operator overloading in general),
    <li> the <code>this</code> pointer,
    <li> the copy constructor.
    </ul>
<p>
<a name="l111"></a>
<h2>7.1: The operators `new' and `delete'</h2>
    <a name="memory/new"></a><strong>C++</strong> defines two operators to allocate and deallocate memory. These
operators are <a name="an946"></a>
<code>new</code> and <a name="an947"></a>
<code>delete</code>.
<p>
The most basic example of the use of these operators is given below. An
<code>int</code> pointer variable is used to point to memory which is allocated by the
operator <code>new</code>. This memory is later released by the operator <code>delete</code>.
        <pre>
    int *ip;

    ip = new int;
    delete ip;
</pre>
    Note that <code>new</code> and <code>delete</code> are <em>operators</em> and therefore do not
require parentheses, as required for <em>functions</em> like <code>malloc()</code> and
<code>free()</code>. The operator <code>delete</code> returns <code>void</code>, the operator <code>new</code>
returns a pointer to the kind of memory that's asked for by its argument
(e.g., a pointer to an <code>int</code> in the above example). Note that the operator
<code>new</code> uses a <em>type</em> as its operand, which has the benefit that the correct
amount of memory, given the type of the object to be allocated, becomes
automatically available. Furthermore, this is a <a name="an948"></a>
type safe procedure as
<code>new</code> returns a pointer to the type that was given as its operand, which
pointer must match the type of the variable receiving the pointervalue.
<p>
The operator <code>new</code> can be used to <a name="an949"></a>
allocate primitive types and to
    <a name="an950"></a>
allocate objects. When a non-class type is allocated (a primitive type
or a <code>struct</code> type without a constructor), the allocated memory is <em>not</em>
guaranteed to be initialized to 0. Alternatively, an <a name="an951"></a>
initialization
expression may be provided:
        <pre>
    int *v1 = new int;          // not guaranteed to be initialized to 0
    int *v1 = new int();        // initialized to 0
    int *v2 = new int(3);       // initialized to 3
    int *v3 = new int(3 * *v2); // initialized to 9
</pre>
    When class-type objects are allocated, the constructor must be mentioned,
and the allocated memory will be initialized according to the constructor that
is used. For example, to allocate a <code>string</code> object the following statement
can be used:
    <pre>
        string *s = new string();
</pre>
    Here, the default constructor was used, and <code>s</code> will point to the newly
allocated, but empty, <code>string</code>. If overloaded forms of the constructor are
available, these can be used as well. E.g.,
    <pre>
        string *s = new string("hello world");
</pre>
    which results in <code>s</code> pointing to a <code>string</code> containing the text
<code>hello world</code>.
<p>
Memory allocation may fail. What happens then is unveiled in section
<a href="cplusplus07.html#NEWHANDLER">7.2.2</a>.
<p>
<a name="NEWARRAY"></a><a name="l112"></a>
<h3>7.1.1: Allocating arrays</h3>
        <a name="memory/newarray"></a>Operator <a name="an952"></a>
<code>new[]</code> is used to <a name="an953"></a>
allocate arrays. The generic <a name="an954"></a>
notation
<code>new[]</code> is an abbreviation used in the Annotations. Actually, the number of
elements to be allocated is specified as an expression between the square
brackets, which are <em>prefixed</em> by the type of the values or class of the
objects that must be allocated:
        <pre>
        int *intarr = new int[20];   // allocates 20 ints
</pre>
    Note well that <a name="an955"></a>
<code>operator new</code> is a different operator than <code>operator
new[]</code>.  In section <a href="cplusplus09.html#NEWDELETEARRAY">9.9</a> redefining <code>operator new[]</code> is
covered.
<p>
Arrays allocated by <code>operator new[]</code> are called <a name="an956"></a>
<em>dynamic arrays</em>.
They are constructed during the execution of a program, and their lifetime may
exceed the lifetime of the function in which they were created. Dynamically
allocated arrays may last for as long as the program runs.
<p>
When <code>new[]</code> is used to allocate an array of primitive values or an
        <a name="an957"></a>
 array of objects, <code>new[]</code> must be
specified with a type and an (unsigned) expression between square
brackets. The type and expression together are used by the compiler to
determine the required size of the block of memory to make available. With the
array allocation, all elements are stored consecutively in memory. The
    <a name="an958"></a>
array index notation can be used to access the individual elements:
<code>intarr[0]</code> will be the very first <code>int</code> value, immediately followed by
<code>intarr[1]</code>, and so on until the last element: <code>intarr[19]</code>. With
non-class types (primitive types, <code>struct</code> types without constructors,
pointer types) the returned allocated block of memory is <em>not</em> guaranteed to
be initialized to 0.
<p>
To <a name="an959"></a>
allocate arrays of objects, the <code>new[]</code>-bracket notation is used
as well. For example, to allocate an array of 20 <code>string</code> objects the
following construction is used:
        <pre>
        string *strarr = new string[20];   // allocates 20 strings
</pre>
    Note here that, since <em>objects</em> are allocated, constructors are
automatically used. So, whereas <code>new int[20]</code> results in a block of 20
<em>uninitialized</em> <code>int</code> values, <code>new string[20]</code> results in a block of 20
<em>initialized</em> <code>string</code> objects. With arrays of objects the
    <a name="an960"></a>
<em>default constructor</em> is used for the initialization. Unfortunately it
is not possible to use a constructor having arguments when arrays of objects
are allocated.  However, it is possible to <em>overload</em> <a name="an961"></a>
<code>operator new[]</code> and
provide it with arguments which may be used for a non-default initialization
of arrays of objects. Overloading <code>operator new[]</code> is discussed in section
<a href="cplusplus09.html#NEWDELETEARRAY">9.9</a>.
<p>
Similar to <strong>C</strong>, and without resorting to the operator <code>new[]</code>, arrays
of variable size can also be constructed as <a name="an962"></a>
<em>local arrays</em> within
functions. Such arrays are not dynamic arrays, but <a name="an963"></a>
<em>local arrays</em>, and
their lifetime is restricted to the lifetime of the block in which they were
defined.
    <blockquote>
    Once allocated, all arrays are <a name="an964"></a>

    <a name="an965"></a>
fixed size arrays. There is no simple way to enlarge or
    <a name="an966"></a>
shrink arrays: there is no <a name="an967"></a>
<code>renew operator</code>. In section
    <a href="cplusplus07.html#ENLARGEARRAY">7.1.3</a> an example is given showing how to
    <a name="an968"></a>
enlarge an array.
    </blockquote>
<p>
<a name="DELETEARRAY"></a><a name="l113"></a>
<h3>7.1.2: Deleting arrays</h3>
        <a name="memory/deletearray"></a>A dynamically allocated array may be deleted using operator
    <a name="an969"></a>
<code>delete[]</code>. Operator <code>delete[]</code> expects a pointer to a block of
memory, previously allocated using operator <a name="an970"></a>
<code>new[]</code>.
<p>
When an object is deleted, its <em>destructor</em> (see section
<a href="cplusplus07.html#DESTRUCTOR">7.2</a>) is called automatically, comparable to the calling of the
object's constructor when the object was created. It is the task of the
destructor, as discussed in depth <a href="cplusplus07.html#DESTRUCTOR">later in this chapter</a>, to
do all kinds of cleanup operations that are required for the proper
destruction of the object.
<p>
The operator <code>delete[]</code> (empty square brackets) expects as its argument
a pointer to an <a name="an971"></a>
array of objects. This operator will now first call the
destructors of the individual objects, and will then delete the allocated
block of memory. So, the proper way to delete an array of <code>Objects</code> is:
        <pre>
    Object *op = new Object[10];
    delete[] op;
</pre>
    Realize that <code>delete[]</code> only has an additional effect if the block of
memory to be deallocated consists of <em>objects</em>. With pointers or values of
primitive types normally no special action is performed. Following
    <code>int *it = new int[10]</code> the statement <code>delete[] it</code> the memory
occupied by all ten <code>int</code> values is returned to the common pool. Nothing
special happens.
<p>
Note especially that an <a name="an972"></a>
<code>array of pointers to objects</code> is not handled as an
<a name="an973"></a>
<code>array of objects</code> by <code>delete[]</code>: the array of pointers to objects doesn't
contain objects, so the objects are not properly destroyed by <code>delete[]</code>,
whereas an array of objects contains objects, which are properly destroyed by
<code>delete[]</code>. In section <a href="cplusplus07.html#DESTRUCTOR">7.2</a> several examples of the use of
<code>delete</code> <em>versus</em> <code>delete[]</code> will be given.
<p>
The operator <code>delete</code> is a different operator than operator
<code>delete[]</code>. In section <a href="cplusplus09.html#NEWDELETEARRAY">9.9</a> redefining <code>delete[]</code> is
discussed. The <a name="an974"></a>
rule of thumb is: if <a name="an975"></a>
<code>new[]</code> was used, also use
<code>delete[]</code>.
<p>
<a name="ENLARGEARRAY"></a><a name="l114"></a>
<h3>7.1.3: Enlarging arrays</h3>
        <a name="memory/enlargearray"></a>Once allocated, all arrays are <a name="an976"></a>
arrays of fixed size.
There is no simple way to enlarge or <a name="an977"></a>
shrink arrays: there is no
    <a name="an978"></a>
<code>renew operator</code>. In this section an example is given showing how to
<a name="an979"></a>
enlarge an array.  Enlarging arrays is only possible with <a name="an980"></a>
dynamic arrays.
Local and global arrays cannot be enlarged.  When an array must be enlarged,
the following procedure can be used:
    <ul>
    <li> Allocate a new block of memory, of larger size
    <li> Copy the old array contents to the new array
    <li> Delete the old array (see section <a href="cplusplus07.html#DELETEARRAY">7.1.2</a>)
    <li> Have the old array pointer point to the newly allocated array
    </ul>
    The following example focuses on the enlargement of an array of <code>string</code>
objects:
    <pre>
    #include &lt;string&gt;
    using namespace std;

    string *enlarge(string *old, unsigned oldsize, unsigned newsize)
    {
        string *tmp = new string[newsize];  // allocate larger array

        for (unsigned idx = 0; idx &lt; oldsize; ++idx)
            tmp[idx] = old[idx];            // copy old to tmp

        delete[] old;                       // using [] due to objects

        return tmp;                         // return new array
    }

    int main()
    {
        string *arr = new string[4];        // initially: array of 4 strings

        arr = enlarge(arr, 4, 6);           // enlarge arr to 6 elements.
    }
</pre>
<p>
<a name="DESTRUCTOR"></a><a name="l115"></a>
<h2>7.2: The destructor</h2>
    <a name="memory/destruc"></a>Comparable to the constructor, classes may define a <a name="an981"></a>
<em>destructor</em>.  This
function is the opposite of the constructor in the sense that it is invoked
when an object ceases to exist. For objects which are local non-static
variables, the destructor is called when the block in which the object is
defined is left: the destructors of objects that are defined in nested blocks
of functions are therefore usually called before the function itself
terminates. The destructors of objects that are defined somewhere in the outer
block of a function are called just before the function returns
(terminates). For static or global variables the destructor is called before
the program terminates.
<p>
However, when a program is interrupted using an <a name="an982"></a>
<code>exit()</code> call, the
destructors are called <em>only</em> for global objects existing at that time.
Destructors of objects defined <em>locally</em> within functions are not called
when a program is forcefully terminated using <code>exit()</code>.
<p>
The definition of a destructor must obey the following  rules:
    <ul>
    <li> The destructor has the same name as the class but its name is
prefixed by a tilde.
    <li> The destructor has no arguments and has no return value.
    </ul>
    The destructor for the class <code>Person</code> is thus declared as follows:
        <pre>
    class Person
    {
        public:
            Person();               // constructor
            ~Person();              // destructor
    };
</pre>
    The position of the constructor(s) and destructor in the class definition
is dictated by convention: first the constructors are declared, then the
destructor, and only then other members are declared.
<p>
The main task of a destructor is to make sure that memory allocated by the
object (e.g., by its constructor) is properly deleted when the object goes out
of scope. Consider the following definition of the class <code>Person</code>:
        <pre>
    class Person
    {
        char *d_name;
        char *d_address;
        char *d_phone;

        public:
            Person();
            Person(char const *name, char const *address,
                   char const *phone);
            ~Person();

            char const *name() const;
            char const *address() const;
            char const *phone() const;
    };

        inline Person::Person()
        {}

/*
    person.ih contains:

    #include "person.h"
    char const *strdupnew(char const *org);
*/
</pre>
    The task of the constructor is to initialize the data fields of the
object. E.g, the constructor is defined as follows:
        <pre>
    #include "person.ih"

    Person::Person(char const *name, char const *address, char const *phone)
    :
        d_name(strdupnew(name)),
        d_address(strdupnew(address)),
        d_phone(strdupnew(phone))
    {}
</pre>
    In this class the destructor is necessary to prevent that memory,
allocated for the fields <code>d_name</code>, <code>d_address</code> and <code>d_phone</code>, becomes
unreachable when an object ceases to exist, thus producing a
    <a name="an983"></a>
memory leak. The destructor of an object is called automatically
    <ul>
    <li> When an object goes out of scope;
    <li> When a dynamically allocated object is deleted;
    <li> When a dynamically allocated array of objects is deleted using the
<a name="an984"></a>
<code>delete[]</code> operator (see section <a href="cplusplus07.html#DELETEARRAY">7.1.2</a>).
    </ul>
    Since it is the task of the destructor to delete all memory that was
dynamically allocated and used by the object, the task of the <code>Person</code>'s
destructor would be to delete the memory to which its three data
members point. The implementation of the destructor would therefore be:
        <pre>
    #include "person.ih"

    Person::~Person()
    {
        delete d_name;
        delete d_address;
        delete d_phone;
    }
</pre>
    In the following example a <code>Person</code> object is created, and its data
fields are printed. After this the <code>showPerson()</code> function stops, resulting
in the deletion of memory.  Note that in this example a second
object of the class <code>Person</code> is created and destroyed dynamically by
respectively, the operators <code>new</code> and <code>delete</code>.
        <pre>
    #include "person.h"
    #include &lt;iostream&gt;

    void showPerson()
    {
        Person karel("Karel", "Marskramerstraat", "038 420 1971");
        Person *frank = new Person("Frank", "Oostumerweg", "050 403 2223");

        cout &lt;&lt; karel.name()     &lt;&lt; ", " &lt;&lt;
                karel.address()  &lt;&lt; ", " &lt;&lt;
                karel.phone()    &lt;&lt; endl &lt;&lt;
                frank-&gt;name()    &lt;&lt; ", " &lt;&lt;
                frank-&gt;address() &lt;&lt; ", " &lt;&lt;
                frank-&gt;phone()   &lt;&lt; endl;

        delete frank;
    }
</pre>
    The memory occupied by the object <code>karel</code> is deleted automatically when
<code>showPerson()</code> terminates: the <strong>C++</strong> compiler makes sure that the
destructor is called. Note, however, that the object pointed to by <code>frank</code>
is handled differently. The variable <code>frank</code> is a pointer, and a pointer
variable is itself no <code>Person</code>. Therefore, before <code>main()</code> terminates, the
memory occupied by the object pointed to by <code>frank</code> should be <em>explicitly</em>
deleted; hence the statement <code>delete</code> <code>frank</code>. The operator <code>delete</code>
will make sure that the destructor is called, thereby deleting the three
<code>char *</code> strings of the object.
<p>
<a name="DELETEPTRS"></a><a name="l116"></a>
<h3>7.2.1: New and delete and object pointers</h3>
        <a name="memory/objectp"></a>    The operators <code>new</code> and <code>delete</code> are used when an object of a given
class is allocated. As we have seen, one of the advantages of
the operators <code>new</code> and <code>delete</code> over functions like <a name="an985"></a>
<code>malloc()</code> and
<a name="an986"></a>
<code>free()</code> is that <code>new</code> and <code>delete</code> call the corresponding
constructors and destructors. This is illustrated in the next example:
        <pre>
    Person *pp = new Person();  // ptr to Person object

    delete pp;                  // now destroyed
</pre>
    The <a name="an987"></a>
allocation of a new <code>Person</code> object pointed to by <code>pp</code> is a
two-step process. First, the memory for the object itself is
allocated. Second, the constructor is called, initializing the object. In
the above example the constructor is the argument-free version; it is however
also possible to use a constructor having arguments:
        <pre>
    frank = new Person("Frank", "Oostumerweg", "050 403 2223");
    delete frank;
</pre>
    Note that, analogously to the <em>construction</em> of an object, the
<em>destruction</em> is also a two-step process: first, the destructor of the class
is called to delete the memory allocated and used by the object; then the
memory which is used by the object itself is freed.
<p>
Dynamically allocated arrays of objects can also be manipulated by
<code>new</code> and <code>delete</code>. In this case the size of the array is given between
the <code>[]</code> when the array is created:
        <pre>
    Person *personarray = new Person [10];
</pre>
    The compiler will generate code to call the default constructor for each
object which is created. As we have seen in section <a href="cplusplus07.html#DELETEARRAY">7.1.2</a>, the
<a name="an988"></a>
<code>delete[]</code> operator must be used here  to destroy such an array in the
proper way:
        <pre>
    delete[] personarray;
</pre>
    The presence of the <code>[]</code> ensures that the destructor is called for each
object in the array.
<p>
What happens if <code>delete</code> rather than <code>delete[]</code> is used? Consider the
following situation, in which the destructor <code>~Person()</code> is modified so that
it will tell us that it's called.  In a <code>main()</code> function an array of two
<code>Person</code> objects is allocated by <code>new</code>, to be deleted by <code>delete
[]</code>. Next, the same actions are repeated, albeit that the <code>delete</code> operator
is called without <code>[]</code>:
        <pre>
    #include &lt;iostream&gt;
    #include "person.h"
    using namespace std;

    Person::~Person()
    {
        cout &lt;&lt; "Person destructor called" &lt;&lt; endl;
    }

    int main()
    {
        Person *a  = new Person[2];

        cout &lt;&lt; "Destruction with []'s" &lt;&lt; endl;
        delete[] a;

        a = new Person[2];

        cout &lt;&lt; "Destruction without []'s" &lt;&lt; endl;
        delete a;

        return 0;
    }
/*
    Generated output:
Destruction with []'s
Person destructor called
Person destructor called
Destruction without []'s
Person destructor called
*/
</pre>
    Looking at the generated output, we see that the destructors of the
individual <code>Person</code> objects are called if the <code>delete[]</code> syntax is
followed, while only the first object's destructor is called if the <code>[]</code> is
omitted.
<p>
If no destructor is defined, it is not called. This may seem to be a
trivial statement, but it has severe implications: objects which allocate
memory will result in a <a name="an989"></a>
memory leak when <a name="an990"></a>
no destructor is defined.
Consider the following program:
        <pre>
    #include &lt;iostream&gt;
    #include "person.h"
    using namespace std;

    Person::~Person()
    {
        cout &lt;&lt; "Person destructor called" &lt;&lt; endl;
    }

    int main()
    {
        Person **a = new Person* [2];

        a[0] = new Person[2];
        a[1] = new Person[2];

        delete[] a;

        return 0;
    }
</pre>
    This program produces no output at all. Why is this? The variable <code>a</code> is
defined as a <a name="an991"></a>
<em>pointer to a pointer</em>. For this situation, however, there
is no defined destructor. Consequently, <a name="an992"></a>
 the <code>[]</code> is
ignored.
<p>
Now, as the <code>[]</code> is ignored, only the array <code>a</code> itself
is deleted, because here `<code>delete[] a</code>' deletes the memory pointed to
by <code>a</code>. That's all there is to it.
<p>
Of course, we don't want this, but require the <code>Person</code> objects pointed
to by the elements of <code>a</code> to be deleted too. In this case we have two
options:
    <ul>
    <li> Explicitly walk all the elements of the <code>a</code> array, deleting them in
turn. This will call the destructor for a pointer to <code>Person</code> objects, which
will destroy all elements if the <code>[]</code> operator is used, as in:
        <pre>
    #include &lt;iostream&gt;
    #include "person.h"

    Person::~Person()
    {
        cout &lt;&lt; "Person destructor called" &lt;&lt; endl;
    }

    int main()
    {
        Person **a = new Person* [2];

        a[0] = new Person[2];
        a[1] = new Person[2];

        for (int index = 0; index &lt; 2; index++)
            delete[] a[index];

        delete[] a;
    }
    /*
        Generated output:
Person destructor called
Person destructor called
Person destructor called
Person destructor called
    */
</pre>
    <li> Define a <a name="an993"></a>
wrapper class containing a pointer to <code>Person</code> objects,
and allocate a pointer to this class, rather than a pointer to a pointer to
<code>Person</code> objects. The topic of containing classes in classes,
<em>composition</em>, was discussed in section <a href="cplusplus06.html#Composition">6.4</a>.  Here is an
example showing the deletion of pointers to memory using such a wrapper class:
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    class Informer
    {
        public:
            ~Informer();
    };

        inline Informer::~Informer()
        {
            cout &lt;&lt; "destructor called\n";
        }

    class Wrapper
    {
        Informer *d_i;

        public:
            Wrapper();
            ~Wrapper();
    };

        inline Wrapper::Wrapper()
        :
            d_i(new Informer())
        {}
        inline Wrapper::~Wrapper()
        {
            delete d_i;
        }

    int main()
    {
        delete[] new Informer *[4];    // memory leak: no destructor called

        cout &lt;&lt; "===========\n";

        delete[] new Wrapper[4];       // ok: 4 x destructor called
    }
    /*
        Generated output:
    ===========
    destructor called
    destructor called
    destructor called
    destructor called
    */
</pre>
    </ul>
<p>
<a name="NEWHANDLER"></a><a name="l117"></a>
<h3>7.2.2: The function set_new_handler()</h3>
        <a name="memory/setnew"></a>The <strong>C++</strong> run-time system makes sure that when memory allocation fails, an
error function is activated. By default this function throws a <em>(bad_alloc)
exception</em> (<a name="an994"></a>
) (see section <a href="cplusplus08.html#STDEXC">8.10</a>), terminating
the program. Consequently, in the default case it is never necessary to check
the return value of the operator <code>new</code>. This default behavior may be
modified in various ways. One way to modify this default behavior is to
redefine the function handling failing memory allocation. However, any
user-defined function must comply with the following prerequisites:
    <ul>
    <li> it has no arguments, and
    <li> it returns no value
    </ul>
<p>
The redefined error function might, e.g., print a message and terminate
the program. The user-written error function becomes part of the allocation
system through the function <a name="an995"></a>
<code>set_new_handler()</code>.
<p>
The implementation of an error function is illustrated below&nbsp;(
This implementation applies to the <a name="an996"></a>
Gnu <strong>C/C++</strong> requirements. The actual
try-out of the program given in the example is not encouraged, as it will slow
down the computer enormously due to the resulting use of the operating
system's <a name="an997"></a>
<em>swap area</em>.):
        <pre>
    #include &lt;iostream&gt;
    using namespace std;

    void outOfMemory()
    {
        cout &lt;&lt; "Memory exhausted. Program terminates." &lt;&lt; endl;
        exit(1);
    }

    int main()
    {
        long allocated = 0;

        set_new_handler(outOfMemory);       // install error function

        while (true)                        // eat up all memory
        {
            new int [100000];
            allocated += 100000 * sizeof(int);
            cout &lt;&lt; "Allocated " &lt;&lt; allocated &lt;&lt; " bytes\n";
        }
    }
</pre>
    After installing the error function it is automatically invoked when
memory allocation fails, and the program exits. Note that memory
allocation may fail in indirectly called code as well, e.g., when constructing
or using streams or when strings are duplicated by low-level functions.
<p>
Note that it may <em>not</em> be assumed that the standard <strong>C</strong> functions which
allocate memory, such as <a name="an998"></a>
<code>strdup()</code>, <a name="an999"></a>
<code>malloc()</code>, <a name="an1000"></a>
<code>realloc()</code> etc. will
trigger the <code>new</code> handler when memory allocation fails. This means that once
a <code>new</code> handler is installed, such functions should not automatically be
used in an unprotected way in a <strong>C++</strong> program. An example using
<code>new</code> to  duplicate a string, was given in a rewrite of the function
<code>strdup()</code> (see section <a href="cplusplus07.html#STRDUPNEW">7</a>).
<p>
<a name="l118"></a>
<h2>7.3: The assignment operator</h2>
    <a name="memory/assignment"></a>Variables which are <a name="an1001"></a>
<code>struct</code>s or <code>classes</code> can be directly assigned in
<strong>C++</strong> in the same way that <code>struct</code>s can be assigned in <strong>C</strong>. The default
action of such an assignment for non-class type data members is a straight
<a name="an1002"></a>
byte-by-byte copy from one data member to another.  Now consider the
consequences of this default action in a function such as the following:
        <pre>
    void printperson(Person const &amp;p)
    {
        Person tmp;

        tmp = p;
        cout &lt;&lt; "Name:     " &lt;&lt; tmp.name()       &lt;&lt; endl &lt;&lt;
                "Address:  " &lt;&lt; tmp.address()    &lt;&lt; endl &lt;&lt;
                "Phone:    " &lt;&lt; tmp.phone()      &lt;&lt; endl;
    }
</pre>
    We shall follow the execution of this function step by step.
    <ul>
    <li> The function <code>printperson()</code> expects a reference to a <code>Person</code> as
its parameter <code>p</code>. So far, nothing extraordinary is happening.
    <li> The function defines a local object <code>tmp</code>. This means that the
default constructor of <code>Person</code> is called, which -if defined properly-
resets the pointer fields <code>name</code>, <code>address</code> and <code>phone</code> of the <code>tmp</code>
object to zero.
    <li> Next, the object referenced by <code>p</code> is copied to <code>tmp</code>. By default
this means that <code>sizeof(Person)</code> bytes from <code>p</code> are copied to <code>tmp</code>.
<p>
Now a potentially dangerous situation has arisen. Note that the actual
values in <code>p</code> are <em>pointers</em>, pointing to allocated memory.  Following the
assignment this memory is addressed by two objects: <code>p</code> <em>and</em> <code>tmp</code>.
    <li> The potentially dangerous situation develops into an acutely
dangerous situation when the function <code>printperson()</code> terminates: the object
<code>tmp</code> is destroyed. The destructor of the class <code>Person</code> releases the
memory pointed to by the fields <code>name</code>, <code>address</code> and <code>phone</code>:
unfortunately, this memory is also in use by <code>p</code>....
    The incorrect assignment is illustrated in Figure <a href="cplusplus07.html#badassign">5</a>.
<p>
<a name="badassign"></a><p><center><img src="memory/badassign.gif" align="bottom" alt="Figure 5 is shown here."/><br>
Figure 5: Private data and public interface functions of the class Person,
    using byte-by-byte assignment
</center><p><br>

    </ul>
    Having executed <code>printperson()</code>, the object which was referenced by
<code>p</code> now contains <a name="an1003"></a>
pointers to deleted memory.
<p>
This situation is undoubtedly not a desired effect of a function like the
above. The deleted memory will likely become occupied during subsequent
allocations: the pointer members of <code>p</code> have effectively become
    <a name="an1004"></a>
 <em>wild pointers</em>, as they don't point to allocated
memory anymore. In general it can be concluded that
    <center><em>every class containing pointer data members is a potential
        candidate for trouble</em>.</center>
    Fortunately, it is possible to prevent these troubles, as discussed in the
next section.
<p>
<a name="OVERLOADASSIGN"></a><a name="l119"></a>
<h3>7.3.1: Overloading the assignment operator</h3>
        <a name="memory/overload"></a>Obviously, the right way to assign one <code>Person</code> object to another, is
<strong>not</strong> to copy the contents of the object bytewise. A better way is to
make an equivalent object: one with its own allocated  memory, but which
contains the same strings.
<p>
The `right' way to <a name="an1005"></a>
 <a name="an1006"></a>
 duplicate a
<code>Person</code> object is illustrated in
    Figure <a href="cplusplus07.html#rightass">6</a>.
    <a name="rightass"></a><p><center><img src="memory/rightass.gif" align="bottom" alt="Figure 6 is shown here."/><br>
Figure 6: Private data and public interface functions of the class Person,
     using the `correct' assignment.
</center><p><br>

    There are several ways to duplicate a <code>Person</code> object.  One way would be
to define a special member function to handle assignments of objects of the
class <code>Person</code>. The purpose of this member function would be to create a
copy of an object, but one with its own <code>name</code>, <code>address</code> and <code>phone</code>
strings.  Such a member function might be:
        <pre>
    void Person::assign(Person const &amp;other)
    {
        // delete our own previously used memory
        delete d_name;
        delete d_address;
        delete d_phone;

        // now copy the other Person's data
        d_name = strdupnew(other.d_name);
        d_address = strdupnew(other.d_address);
        d_phone = strdupnew(other.d_phone);
    }
</pre>
    Using this tool we could rewrite the offending function <code>printperson()</code>:
        <pre>
    void printperson(Person const &amp;p)
    {
        Person tmp;

        // make tmp a copy of p, but with its own allocated memory
        tmp.assign(p);

        cout &lt;&lt; "Name:     " &lt;&lt; tmp.name()       &lt;&lt; endl &lt;&lt;
                "Address:  " &lt;&lt; tmp.address()    &lt;&lt; endl &lt;&lt;
                "Phone:    " &lt;&lt; tmp.phone()      &lt;&lt; endl;

        // now it doesn't matter that tmp gets destroyed..
    }
</pre>
    By itself this solution is valid, although it is a purely symptomatic
solution.  This solution requires the programmer to use a specific member
function instead of the operator <code>=</code>. The basic problem, however, remains if
this rule is not strictly adhered to. Experience learns that <em>errare humanum
est</em>: a solution which doesn't enforce special actions is therefore
preferable.
<p>
The problem of the assignment operator is solved using <em>operator
overloading</em>: the syntactic possibility <strong>C++</strong> offers to redefine the actions
of an operator in a given context. Operator overloading was mentioned earlier,
when the operators << and >> were redefined to be used with
streams (like <code>cin</code>, <code>cout</code> and <code>cerr</code>), see section <a href="cplusplus03.html#CoutCinCerr">3.1.2</a>.
<p>
Overloading the assignment operator is probably the most common form of
operator overloading. However, a word of warning is appropriate: the fact that
<strong>C++</strong> allows <a name="an1007"></a>
operator overloading does not mean that this feature should
be used at all times. A few rules are:
    <ul>
    <li> Operator overloading should be used in situations where an operator
has a defined action, but when this action is not desired as it has negative
side effects. A typical example is the above assignment operator in the
context of the class <code>Person</code>.
    <li> Operator overloading can be used in situations where the use of the
operator is common and when no <a name="an1008"></a>
ambiguity in the meaning of the operator is
introduced by redefining it. An example may be the redefinition of the
operator <code>+</code> for a class which represents a complex number. The meaning of a
<code>+</code> between two complex numbers is quite clear and unambiguous.
    <li> In all other cases it is preferable to define a member function,
instead of redefining an operator.
        </ul>
    Using these rules, operator overloading is minimized which helps keep
source files readable. An operator simply does what it is designed to
do. Therefore, I consider overloading the insertion (<<) and extraction
(>>) operators in the context of streams ill-chosen: the stream
operations do not have anything in common with the bitwise shift operations.
<p>
<a name="l120"></a>
<strong>7.3.1.1: The member 'operator=()'</strong>
        <a name="memory/operator"></a>To achieve operator overloading in the context of a class, the class is simply
expanded with a (usually <em>public</em>) member function naming the particular
operator. That member function is thereupon defined.
<p>
For example, to overload the assignment operator <code>=</code>, a function
<code>operator=()</code> must be defined. Note that the function name consists of two
parts: the keyword <a name="an1009"></a>
<code>operator</code>, followed by the operator itself.  When we
augment a class interface with a member function <code>operator=()</code>, then that
operator is <em>redefined</em> for the class, which prevents the default operator
from being used. Previously (in section <a href="cplusplus07.html#OVERLOADASSIGN">7.3.1</a>) the function
<code>assign()</code> was offered to solve the memory-problems resulting from using the
default assignment operator. However, instead of using an ordinary member
function it is much more common in <strong>C++</strong> to define a dedicated <em>operator</em>
for these special cases. So, the earlier <code>assign()</code> member may be redefined
as follows (note that the member <code>operator=()</code> presented below is a first,
rather unsophisticated, version of the overloaded assignment operator.  It
will be improved shortly):
        <pre>
    class Person
    {
        public:                             // extension of the class Person
                                            // earlier members are assumed.
            void operator=(Person const &amp;other);
    };
</pre>
    and its implementation could be
        <pre>
    void Person::operator=(Person const &amp;other)
    {
        delete d_name;                      // delete old data
        delete d_address;
        delete d_phone;

        d_name = strdupnew(other.d_name);   // duplicate other's data
        d_address = strdupnew(other.d_address);
        d_phone = strdupnew(other.d_phone);
    }
</pre>
    The actions of this member function are similar to those of the previously
proposed function <code>assign()</code>, but now its <em>name</em> ensures that this
function is also activated when the assignment operator <code>=</code> is used. There
are actually two ways to <a name="an1010"></a>
call overloaded operators:
        <pre>
    Person pers("Frank", "Oostumerweg", "403 2223");
    Person copy;

    copy = pers;                // first possibility
    copy.operator=(pers);       // second possibility
</pre>
    Actually, the second possibility, explicitly calling <code>operator=()</code>, is
not used very often. However, the code fragment <em>does</em> illustrate two
ways to call the same overloaded operator member function.
<p>
<a name="l121"></a>
<h2>7.4: The `this' pointer</h2>
    <a name="memory/this"></a>As we have seen, a member function of a given class is always called in the
context of some object of the class. There is always an implicit `<a name="an1011"></a>
substrate'
for the function to act on. <strong>C++</strong> defines a keyword, <a name="an1012"></a>
<code>this</code>, to address
this substrate&nbsp;(Note that `<code>this</code>' is not available in the not yet
discussed <code>static</code> member functions.).
<p>
The <code>this</code> keyword is a pointer variable, which always contains the address
<a name="an1013"></a>
 <a name="an1014"></a>

of the object in question. The <code>this</code> pointer is implicitly declared in each
member function (whether <code>public, protected</code>, or <code>private</code>). Therefore, it
is as if each member function of the class <code>Person</code> contains the
following declaration:
        <pre>
    extern Person *const this;
</pre>
    A member function like <code>name()</code>, which returns the <code>name</code> field of
a <code>Person</code>, could therefore be implemented in two ways: with or without the
<code>this</code> pointer:
        <pre>
    char const *Person::name()   // implicit usage of `this'
    {
        return d_name;
    }

    char const *Person::name()   // explicit usage of `this'
    {
        return this-&gt;d_name;
    }
</pre>
    The <code>this</code> pointer is not frequently used explicitly.
However, situations do exist where the <code>this</code> pointer is actually required
(cf. chapter <a href="cplusplus15.html#PointMembers">15</a>).
<p>
<a name="l122"></a>
<h3>7.4.1: Preventing self-destruction using `this'</h3>
        <a name="memory/prevent"></a>As we have seen, the operator <code>=</code> can be redefined for the class
<code>Person</code> in such a way that two objects of the class can be assigned,
resulting in two copies of the same object.
<p>
As long as the two variables are different ones, the previously presented
version of the function <code>operator=()</code> will behave properly: the memory of
the assigned object is released, after which it is allocated again to hold new
strings. However, when an object is assigned to itself (which is called
<a name="an1015"></a>
<em>auto-assignment</em>), a problem occurs: the allocated strings of the
receiving object are first deleted, resulting in the deletion of the
memory of the right-hand side variable, which we call <a name="an1016"></a>
<em>self-destruction</em>.
An example of this situation is illustrated here:
        <pre>
    void fubar(Person const &amp;p)
    {
        p = p;          // auto-assignment!
    }
</pre>
    In this example it is perfectly clear that something unnecessary, possibly
even wrong, is happening. But auto-assignment can also occur in more hidden
forms:
        <pre>
    Person one;
    Person two;
    Person *pp = &amp;one;

    *pp = two;
    one = *pp;
</pre>
    The problem of auto-assignment can be solved using the <a name="an1017"></a>
<code>this</code>
pointer. In the <a name="an1018"></a>
overloaded assignment operator function we simply test
whether the address of the right-hand side object is the same as the address
of the current object: if so, no action needs to be taken. The definition of
the function <code>operator=()</code> thus becomes:
        <pre>
    void Person::operator=(Person const &amp;other)
    {
        // only take action if address of the current object
        // (this) is NOT equal to the address of the other object

        if (this != &amp;other)
        {
            delete d_name;
            delete d_address;
            delete d_phone;

            d_name = strdupnew(other.d_name);
            d_address = strdupnew(other.d_address);
            d_phone = strdupnew(other.d_phone);
        }
    }
</pre>
    This is the second version of the overloaded assignment function. One, yet
better version remains to be discussed.
<p>
As a subtlety, note the usage of the <em>address operator</em> '<code>&amp;</code>'
in the statement
        <pre>
    if (this != &amp;other)
</pre>
    The variable <code>this</code> is a pointer to the `current' object, while
<code>other</code> is a reference; which is an `alias' to an actual <code>Person</code>
object. The address of the other object is therefore <code>&amp;other</code>, while the
address of the current object is <code>this</code>.
<p>
<a name="l123"></a>
<h3>7.4.2: Associativity of operators and this</h3>
        <a name="memory/associat"></a>    According to <strong>C++</strong>'s syntax, the assignment operator associates from
right to left. I.e., in statements like:
        <pre>
    a = b = c;
</pre>
    the expression <code>b = c</code> is evaluated first, and the result is assigned to
<code>a</code>.
<p>
So far, the implementation of the overloaded assignment operator does not
permit such constructions, as an assignment using the member function returns
nothing (<code>void</code>). We can therefore conclude that the previous implementation
does solve an allocation problem, but concatenated assignments are still not
allowed.
<p>
The problem can be illustrated as follows. When we rewrite the expression
<code>a = b = c</code> to the form which explicitly mentions the overloaded assignment
member functions, we get:
        <pre>
        a.operator=(b.operator=(c));
</pre>
    This variant is syntactically wrong, since the sub-expression
<code>b.operator=(c)</code> yields <code>void</code>. However, the class <code>Person</code> contains no
member functions with the prototype <code>operator=(void)</code>.
<p>
This problem too can be remedied using the <a name="an1019"></a>
<code>this</code> pointer. The
<a name="an1020"></a>
overloaded assignment function expects as its argument a reference to a
<code>Person</code> object. It can also <em>return</em> a reference to such an
object. This reference can then be used as an argument in a
    <a name="an1021"></a>
concatenated assignment.
<p>
It is customary to let the overloaded assignment return a
    <a name="an1022"></a>
reference to the current object (i.e., <code>*this</code>).  The (final) version
of the overloaded assignment operator for the class <code>Person</code> thus becomes:
        <pre>
    Person &amp;Person::operator=(Person const &amp;other)
    {
        if (this != &amp;other)
        {
            delete d_address;
            delete d_name;
            delete d_phone;

            d_address = strdupnew(other.d_address);
            d_name = strdupnew(other.d_name);
            d_phone = strdupnew(other.d_phone);
        }
        // return current object. The compiler will make sure
        // that a reference is returned
        return *this;
    }
</pre>
<p>
<a name="l124"></a>
<h2>7.5: The copy constructor: initialization vs. assignment</h2>
    <a name="memory/initialisation"></a>In the following sections we shall take a  closer look at another usage of the
operator <code>=</code>. Consider, once again, the <code>class Person</code>. The class has the
following characteristics:
    <ul>
    <li> The class contains several pointers, possibly pointing to
allocated memory. As discussed, such a class needs a constructor and a
destructor.
<p>
A typical action of the constructor would be to set the pointer members to
0. A typical action of the destructor would be to delete the
allocated memory.
    <li> For the same reason the class requires an overloaded assignment
operator.
    <li> The class has, besides a default constructor, a constructor which
expects the name, address and phone number of the <code>Person</code> object.
    <li> For now, the only remaining interface functions return the name,
address or phone number of the <code>Person</code> object.
    </ul>
    Now consider the following code fragment. The statement references are
discussed following the example:
        <pre>
    Person karel("Karel", "Marskramerstraat", "038 420 1971"); // see (1)
    Person karel2;                                             // see (2)
    Person karel3 = karel;                                     // see (3)

    int main()
    {
        karel2 = karel3;                                    // see (4)
        return 0;
    }
</pre>
    <ul>
    <li> Statement 1: this shows an <a name="an1023"></a>
initialization.  The object
<code>karel</code> is initialized with appropriate texts. This construction of
<code>karel</code> therefore uses the constructor expecting three <code>char
const *</code> arguments.
<p>
Assume a <code>Person</code> constructor is available having only one <code>char const
*</code> parameter, e.g.,
        <pre>
    Person::Person(char const *n);
</pre>
    It should be noted that the initialization `<code>Person frank("Frank")</code>' is
identical to
        <pre>
    Person frank = "Frank";
</pre>
    Even though this piece of code uses the operator <code>=</code>, it is no
assignment: rather, it is an <em>initialization</em>, and hence, it's done at
<em>construction time</em> by a constructor of the class <code>Person</code>.
    <li> Statement 2: here a second <code>Person</code> object is created. Again a
constructor is called. As no special arguments are present, the
    <a name="an1024"></a>
<em>default constructor</em> is used.
    <li> Statement 3: again a new object <code>karel3</code> is created. A constructor
is therefore called once more.  The new object is also initialized. This time
with a copy of the data of object <code>karel</code>.
<p>
This form of initializations has not yet been discussed. As we can
rewrite this statement in the form
        <pre>
    Person karel3(karel);
</pre>
    it is suggested that a constructor is called, having a reference to a
<code>Person</code> object as its argument. Such constructors are quite common in
<strong>C++</strong> and are called <a name="an1025"></a>
 <em>copy constructors</em>.
    <li> Statement 4: here one object is assigned to another. No object is
<em>created</em> in this statement. Hence, this is just an <a name="an1026"></a>
assignment, using
the <a name="an1027"></a>
overloaded assignment operator.
    </ul>
<p>
The simple rule emanating from these examples is that <em>whenever an object is
created, a constructor is needed</em>.  All constructors have the following
<a name="an1028"></a>
 characteristics:
    <ul>
    <li> Constructors have no return values.
    <li> Constructors are defined in functions having the same names as the
class to which they belong.
    <li> The actual constructor that is to be used can be
deduced from the constructor's argument list. The assignment operator may be
used if the constructor has only one parameter (and also when
remaining parameters have default argument values).
    </ul>
    Therefore, we conclude that, given the above statement (3), the class
<code>Person</code> must be augmented with a <a name="an1029"></a>
<em>copy constructor</em>:
        <pre>
    class Person
    {
        public:
            Person(Person const &amp;other);
    };
</pre>
    The implementation of the <code>Person</code> copy constructor is:
        <pre>
    Person::Person(Person const &amp;other)
    {
        d_name    = strdupnew(other.d_name);
        d_address = strdupnew(other.d_address);
        d_phone   = strdupnew(other.d_phone);
    }
</pre>
    The actions of copy constructors are comparable to those of the overloaded
assignment operators: an object is <em>duplicated</em>, so that it
will contain its own allocated data. The copy constructor, however, is
simpler in the following respects:
    <ul>
    <li> A copy constructor doesn't need to delete previously allocated
memory: since the object in question has just been created, it cannot already
have its own allocated data.
    <li> A copy constructor never needs to check whether auto-duplication
occurs. No variable can be initialized with itself.
    </ul>
    Apart from the above mentioned quite obvious usage of the copy constructor,
the copy constructor has other important tasks. All of these tasks are related
to the fact that the copy constructor is always called when an object is
initialized using another object of its class.  The copy
constructor is called even when this new object is a hidden or is a temporary
variable.
    <ul>
    <li> When a function takes an <a name="an1030"></a>
object as argument, instead of, e.g., a
pointer or a reference, the copy constructor is called to pass a copy of an
object as the argument. This argument, which usually is passed via the
<a name="an1031"></a>
stack, is therefore a new object. It is created and initialized with the
data of the passed argument.
    This is illustrated in the following code fragment:
        <pre>
    void nameOf(Person p)       // no pointer, no reference
    {                           // but the Person itself
        cout &lt;&lt; p.name() &lt;&lt; endl;
    }

    int main()
    {
        Person frank("Frank");

        nameOf(frank);
        return 0;
    }
</pre>
    In this code fragment <code>frank</code> itself is not passed as an argument, but
instead a temporary (stack) variable is created using the copy
constructor. This temporary variable is known inside <code>nameOf()</code> as
<code>p</code>. Note that if <code>nameOf()</code> would have had a reference parameter, extra
stack usage and a call to the copy constructor would have been avoided.
    <li> The copy constructor is also implicitly called when a function
returns an object:
        <pre>
    Person person()
    {
        string name;
        string address;
        string phone;

        cin &gt;&gt; name &gt;&gt; address &gt;&gt; phone;

        Person p(name.c_str(), address.c_str(), phone.c_str());

        return p;           // returns a copy of `p'.
    }
</pre>
    Here a <a name="an1032"></a>
hidden object of the class <code>Person</code> is initialized, using the
copy constructor, as the value returned by the function. The local variable
<code>p</code> itself ceases to exist when <code>person()</code> terminates.
    </ul>
    To demonstrate that copy constructors are not called in all situations,
consider the following.  We could rewrite the above function <code>person()</code> to
the following form:
        <pre>
    Person person()
    {
        string name;
        string address;
        string phone;

        cin &gt;&gt; name &gt;&gt; address &gt;&gt; phone;

        return Person(name.c_str(), address.c_str(), phone.c_str());
    }
</pre>
    This code fragment is perfectly valid, and illustrates the use of an
<a name="an1033"></a>
<code>anonymous object</code>. Anonymous objects are <a name="an1034"></a>
<em>const objects</em>: their data
members may not change. The use of an anonymous object in the above example
illustrates the fact that <a name="an1035"></a>
object return values should be considered
constant objects, even though the keyword <code>const</code> is not explicitly
mentioned in the return type of the function (as in <code>Person const
person()</code>).
<p>
As an other example, once again assuming the availability of a
<code>Person(char const *name)</code> constructor, consider:
        <pre>
    Person namedPerson()
    {
        string name;

        cin &gt;&gt; name;
        return name.c_str();
    }
</pre>
    Here, even though the return value <code>name.c_str()</code> doesn't match the
return type <code>Person</code>, there is a <em>constructor</em> available to construct a
<code>Person</code> from a <code>char const *</code>. Since such a constructor is available, the
(anonymous) return value can be constructed by <em>promoting</em> a
    <a name="an1036"></a>
 <code>char const *</code> type to a <code>Person</code> type using an
appropriate constructor.
<p>
Contrary to the situation we encountered with the default constructor, the
<a name="an1037"></a>
default copy constructor remains available once a constructor (<em>any
constructor</em>) is defined explicitly. The copy constructor can be redefined,
but if not, then the default copy constructor will still be available when
another constructor is defined.
<p>
<a name="CopyDestroy"></a><a name="l125"></a>
<h3>7.5.1: Similarities between the copy constructor and operator=()</h3>
        <a name="memory/copyopis"></a>The similarities between the <a name="an1038"></a>
copy constructor and the
    <a name="an1039"></a>
overloaded assignment operator are reinvestigated in this section.  We
present here two primitive functions which often occur in our code, and which
we think are quite useful. Note the following features of copy constructors,
overloaded assignment operators, and destructors:
    <ul>
    <li> The <em>copying of (private) data</em> occurs (1) in the copy constructor
and (2) in the overloaded assignment function.
    <li> The <em>deletion of allocated memory</em> occurs (1) in the overloaded
assignment function and (2) in the destructor.
    </ul>
    The above two actions (duplication and deletion) can be implemented in two
private functions, say <a name="an1040"></a>
<code>copy()</code> and <a name="an1041"></a>
<code>destroy()</code>, which are used in the
overloaded assignment operator, the copy constructor, and the destructor. When
we apply this method to the class <code>Person</code>, we can implement this approach
as follows:
    <ul>
    <li> First, the class definition is expanded with two <code>private</code>
functions <code>copy()</code> and <code>destroy()</code>. The purpose of these functions is to
copy the data of another object or to delete the memory of the current
object <em>unconditionally</em>.  Hence these functions implement `primitive'
functionality:
        <pre>
    // class definition, only relevant functions are shown here
    class Person
    {
        char *d_name;
        char *d_address;
        char *d_phone;

        public:
            Person(Person const &amp;other);
            ~Person();
            Person &amp;operator=(Person const &amp;other);
        private:
            void copy(Person const &amp;other);     // new members
            void destroy(void);

    };
</pre>
    <li> Next, the functions <code>copy()</code> and <code>destroy()</code> are constructed:
        <pre>
    void Person::copy(Person const &amp;other)
    {
        d_name = strdupnew(other.d_name);       // unconditional copying
        d_address = strdupnew(other.d_address);
        d_phone = strdupnew(other.d_phone);
    }

    void Person::destroy()
    {
        delete d_name;                        // unconditional deletion
        delete d_address;
        delete d_phone;
    }
</pre>
    <li> Finally the <code>public</code> functions in which other object's memory
is copied or in which memory is deleted are rewritten:
        <pre>
    Person::Person (Person const &amp;other)    // copy constructor
    {
        copy(other);
    }

    Person::~Person()                       // destructor
    {
        destroy();
    }
                                            // overloaded assignment
    Person const &amp;Person::operator=(Person const &amp;other)
    {
        if (this != &amp;other)
        {
            destroy();
            copy(other);
        }
        return *this;
    }
</pre>
    </ul>
    What we like about this approach is that the destructor, copy constructor
and overloaded assignment functions are now completely standard: they are
<em>independent</em> of a particular class, and <em>their implementations can
therefore be used in every class</em>.  Any class dependencies are reduced to the
implementations of the private member functions <code>copy()</code> and <code>destroy()</code>.
<p>
Note, that the <a name="an1042"></a>
<code>copy()</code> member function is responsible for the copying
of the other object's data fields to the current object. We've shown the
situation in which a class <em>only</em> has pointer data members. In most
situations <a name="an1043"></a>
 classes have non-pointer data
members as well. These members must be copied in the copy constructor as
well. This can simply be realized by the copy constructor's body <em>except</em>
for the initialization of <a name="an1044"></a>
reference data members, which <em>must</em> be
initialized using the
    <a name="an1045"></a>
member initializer method, introduced in section
<a href="cplusplus06.html#REFMEMBERS">6.4.2</a>. However, in this case the <a name="an1046"></a>
overloaded assignment operator
can't be fully implemented either, as reference members cannot
be given another value once initialized. An object having reference data
members is inseparately attached to its referenced object(s) once it has been
constructed.
<p>
<a name="l126"></a>
<h3>7.5.2: Preventing certain members from being used</h3>
        <a name="memory/preventing"></a>As we've seen in the previous section, situations may be encountered in which
a member function can't do its job in a completely satisfactory way. In
particular: an <a name="an1047"></a>
overloaded assignment operator cannot do its job completely
if its class contains <a name="an1048"></a>
reference data members. In this and comparable
situations the programmer might want to <em>prevent</em> the (accidental) use of
    <a name="an1049"></a>

    <a name="an1050"></a>
 certain member functions. This can be
realized in the following ways:
    <ul>
    <li> Move all member functions that should not be callable to the
<code>private</code> section of the class interface. This will effectively prevent the
user from the class to use these members. By moving the assignment operator to
the private section, objects of the class cannot be assigned to each other
anymore. Here the <em>compiler</em> will detect the use of a private member outside
of its class and will flag a compilation error.
    <li> The above solution still allows the <em>constructor</em> of the class to
use the unwanted member functions within the class members itself. If that is
deemed undesirable as well, such functions should stil be moved to the private
section of the class interface, <a name="an1051"></a>
 but they
<a name="an1052"></a>
 should not be implemented. The <em>compiler</em>
won't be able to prevent the (accidental) use of these forbidden members, but
the <em>linker</em> won't be able to solve the associated external reference.
    <li> It is <em>not</em> always a good idea to <a name="an1053"></a>
<em>omit member functions</em>
        <a name="an1054"></a>
 that should not be called from the
class interface. In particular, the overloaded assignment operator has a
<em>default</em> implementation that will be used if no overloaded version is
mentioned in the class interface. So, in particular with the overloaded
assignment operator, the previously mentioned approach should be
followed. Moving certain <a name="an1055"></a>
 <a name="an1056"></a>

constructors to the private section of the class interface is also a good
technique to prevent their use by `the general public'.
    </ul>
<p>
<a name="l127"></a>
<h2>7.6: Conclusion</h2>
    <a name="memory/conclusion"></a>Two important extensions to classes have been discussed in this chapter: the
<a name="an1057"></a>
overloaded assignment operator and the <a name="an1058"></a>
copy constructor. As we have
seen, classes with <a name="an1059"></a>
pointer data members, addressing allocated memory, are
potential sources of <a name="an1060"></a>
memory leaks. The two extensions introduced in this
chapter represent the standard way to prevent these memory leaks.
<p>
The simple conclusion is therefore: classes whose objects allocate memory
which is used by these objects themselves, should implement a
<em>destructor</em>, an <em>overloaded assignment operator</em> and a
    <em>copy constructor</em> as well.
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus06.html">Previous Chapter</a>
    <li> <a href="cplusplus08.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
